package org.jeecg.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.qis.entity.QisRuleCfg;
import org.jeecg.qis.service.IQisRuleCfgService;
import org.jeecg.wms.entity.*;
import org.jeecg.wms.mapper.WmsMatdetailValueMapper;
import org.jeecg.wms.mapper.WmsMatheadValueMapper;
import org.jeecg.wms.service.*;
import org.jeecg.wms.vo.WmsMatheadValueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 原料检验单
 * @Author: LiCY
 * @Date:   2025-03-11
 * @Version: V1.0
 */
@Service
public class WmsMatheadValueServiceImpl extends ServiceImpl<WmsMatheadValueMapper, WmsMatheadValue> implements IWmsMatheadValueService {
    @Autowired
    private CommonAPI commonAPI;
    @Autowired
    private IWmsMatdetailCfgService iWmsMatdetailCfgService;
    @Autowired
    private IWmsRuleCfgService iWmsRuleCfgService;
    @Autowired
    private IWmsMatdetailValueService iWmsMatdetailValueService;
    @Autowired
    private IWmsPartdataCfgService iWmsPartdataCfgService;
    @Autowired
    private IWmsMatheadCfgService iWmsMatheadCfgService;

    /**
     * 新增原材料手动检验单
     * @param wmsMatheadValue
     */
    @Override
    public Result<String> saveRecord(WmsMatheadValue wmsMatheadValue) {
        //校验物料版本号
        WmsMatheadCfg one = iWmsMatheadCfgService.getOne(new LambdaQueryWrapper<WmsMatheadCfg>().eq(WmsMatheadCfg::getItempartno, wmsMatheadValue.getPartno()));
        if (one == null){
            return Result.error("未找到该物料！");
        }
        wmsMatheadValue.setCfgid(one.getRecId());
       if (!one.getRev().isEmpty()&&!one.getRev().equals(wmsMatheadValue.getRev())){
           return Result.error("物料版本号不匹配！");
       }
        //新增主单据
        Integer counterValue = commonAPI.getCounterValue("recid.wms_mathead_value","0");
        wmsMatheadValue.setRecId(counterValue);
        wmsMatheadValue.setTrgTyp("2");
        wmsMatheadValue.setResult("2");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        wmsMatheadValue.setUser(sysUser.getUsername());
        this.baseMapper.insert(wmsMatheadValue);
        //新增子单据
        List<WmsMatdetailCfg> detailList =iWmsMatdetailCfgService.getDetailList(wmsMatheadValue);
        //获取抽样方案
        //List<WmsRuleCfg> list = iWmsRuleCfgService.list();
        List<WmsMatdetailValue> matdetailValueArrayList = new ArrayList<>();
        int qty = wmsMatheadValue.getQty().intValue();
        //遍历检测项目 获取抽样数
        detailList.forEach(item->{
            String groupid = item.getGroupid();
            List<WmsRuleCfg> ruleCfgs = iWmsRuleCfgService.list(new QueryWrapper<WmsRuleCfg>()
                    .eq("GROUPID", groupid));
            //iWmsRuleCfgService.getValueByQty(groupid,  qty);
            int ruleQty = 0;
            if (ruleCfgs.isEmpty()){
                ruleQty = 1;
            }else{
                if (ruleCfgs.size()>1){
                    for (WmsRuleCfg ruleCfg : ruleCfgs){
                        if (ruleCfg.getUpLimit().doubleValue()>=qty && qty>=ruleCfg.getLowLimit().doubleValue()){
                            ruleQty = ruleCfg.getValue();
                        }
                    }
                }else {
                    WmsRuleCfg qisRuleCfg = ruleCfgs.get(0);
                    ruleQty = qisRuleCfg.getValue();
                }
            }
            createDetailValue(counterValue, matdetailValueArrayList, item, ruleQty);
        });
        //新增子单据
        iWmsMatdetailValueService.saveBatch(matdetailValueArrayList);
        return Result.OK("创建成功！");
    }

    @Override
    public IPage<WmsMatheadValueVO> pageList(Page<WmsMatheadValueVO> page, WmsMatheadValue wmsMatheadValue) {
        return this.baseMapper.pageList(page, wmsMatheadValue);
    }

    @Override
    public IPage<WmsMatheadValueVO> queryPageHisList(Page<WmsMatheadValueVO> page, WmsMatheadValue wmsMatheadValue) {
        return null;
    }

    private void createDetailValue(Integer counterValue, List<WmsMatdetailValue> matdetailValueArrayList, WmsMatdetailCfg item, Integer value) {
        for (int i = 1; i <= value; i++){
            WmsMatdetailValue wmsMatdetailValue = new WmsMatdetailValue();
            Integer recid = commonAPI.getCounterValue("recid.wms_matdetail_value","0");
            wmsMatdetailValue.setRecId(recid);
            wmsMatdetailValue.setSampleNum(i);
            wmsMatdetailValue.setHeadid(counterValue);
            wmsMatdetailValue.setTn(1);
            wmsMatdetailValue.setDataid(String.valueOf(item.getRecId()));
            wmsMatdetailValue.setStatus("0");
            if(item.getDatatype().equals("1")){
                wmsMatdetailValue.setLowLimit(BigDecimal.valueOf(-1));
                wmsMatdetailValue.setUpLimit(BigDecimal.valueOf(-1));
            }else {
                wmsMatdetailValue.setLowLimit(item.getLowLimit());
                wmsMatdetailValue.setUpLimit(item.getUpLimit());
            }
            matdetailValueArrayList.add(wmsMatdetailValue);
        }
    }

    public static String generateInspectionNumber(Integer sequenceNumber) {
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String datePart = dateFormat.format(new Date());
        // 格式化序号为四位数，不足四位时前面填充0
        String sequencePart = String.format("%04d", sequenceNumber);
        // 组合生成检验单号
        return "MC" + datePart + sequencePart;
    }
}
